# -*- coding:utf-8 -*-
# @Author:🎈RedBalloon
# @Time:2022/9/30-20:08
# @File:12-cookie的使用2.py
from urllib.request import Request, urlopen
from fake_useragent import UserAgent
from urllib.parse import urlencode
# 构造cookie
from urllib.request import HTTPCookieProcessor, build_opener
# 登录
url = "http://www.sxt.cn/index/login/login"
headers = {
    "user-agent": UserAgent().random,
    "Referer": "http://www.996dm.com/index.php/user/login.html"
}
form_data = {
    "user_name": "redballoon",
    "user_pwd": "qwer123456"
}
form_data = urlencode(form_data).encode()
request = Request(url, headers=headers, data=form_data)
# response = urlopen(request).read().decode()

# 如果需要保存cookie需要自己构造opener传入对应的handler
# HTTPCookieProcessor()传入cookiejar参数
handler = HTTPCookieProcessor()
opener = build_opener(handler)
response = opener.open(request)

print(response.read().decode())


# 访问信息页面
info_url = "http://www.sxt.cn/index/user.html"
request = Request(url, headers=headers)
# response = urlopen(request).read().decode()

info_response = opener.open(request)
print(response.read().decode())


# cookielib模块主要提供可存储cookie对象
# 主要对象有：CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar
